import axios, { AxiosRequestConfig, AxiosResponse } from "axios"

import { ElMessage, ElMessageBox } from 'element-plus'

const request = axios.create({
  baseURL: "/api",
  timeout: 5000
})
request.interceptors.request.use((config) => {
  if (localStorage.getItem("token")) {
    config.headers.Authorization = localStorage.getItem("token")
  }
  return config
}, err => {
  return Promise.reject(err.message)
})
request.interceptors.response.use((res: AxiosResponse) => {
  console.log(res.data.code !== 200);
  if (res.data.code !== 200) {

    //当其他登录或者非法登录就要推出登录
    if (res.data.status === 401 || res.status === 400 || res.status === 403) {
      ElMessageBox.confirm(
        '您必须退出登录，点击取消留在页面，点击确定跳转到登录页面',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
        })
        .catch(() => {
        })
      return Promise.reject(res)
    }
  } else {
    return res.data
  }
  return res.data
}, err => {
  ElMessage.error(err.message)
  return Promise.reject(err.message)
})
export default request